<!--
 * @Description: 个人中心页面 - 微信登录和功能管理
 * @Date: 2025-10-10
-->
<template>
  <view class="mine-container">
    <!-- 用户信息区域 -->
    <view class="user-section" v-if="userInfo">
      <view class="user-avatar">
        <image :src="userInfo.avatarUrl" mode="aspectFill" class="avatar-img" />
      </view>
      <view class="user-info">
        <view class="user-name">{{ userInfo.nickName }}</view>
        <view class="user-level">Lv.{{ userInfo.level || 1 }}</view>
      </view>
      <!-- <view class="user-stats">
        <view class="stat-item">
          <view class="stat-number">{{ userInfo.followCount || 0 }}</view>
          <view class="stat-label">关注</view>
        </view>
        <view class="stat-item">
          <view class="stat-number">{{ userInfo.fansCount || 0 }}</view>
          <view class="stat-label">粉丝</view>
        </view>
        <view class="stat-item">
          <view class="stat-number">{{ userInfo.likeCount || 0 }}</view>
          <view class="stat-label">获赞</view>
        </view>
      </view> -->
    </view>

    <!-- 登录区域 -->
    <view class="login-section" v-else>
      <view class="login-card">
        <view class="login-title">欢迎使用POE2通货物价查询</view>
        <view class="login-desc">登录后可以收藏通货、查看历史记录等</view>
        <button
          class="login-btn"
          open-type="chooseAvatar"
          @chooseavatar="onGetUserInfo"
          @tap="handleWechatLogin"
        >
          <view class="btn-content">
            <u-icon name="weixin-circle-fill" size="20" color="#fff" />
            <text class="btn-text">微信一键登录</text>
          </view>
        </button>
        <view class="login-tip">点击登录即表示同意用户协议和隐私政策</view>
      </view>
    </view>

    <!-- Tab切换栏 -->
    <view class="tab-section" v-if="userInfo">
      <view class="tab-header">
        <view
          class="tab-item"
          :class="{ active: currentTab === index }"
          v-for="(tab, index) in tabList"
          :key="tab.key"
          @tap="handleTabChange(index)"
        >
          <view class="tab-icon">{{ tab.icon }}</view>
          <view class="tab-name">{{ tab.name }}</view>
        </view>
      </view>

      <!-- Tab内容区域 -->
      <view class="tab-content">
        <!-- 我的收藏 -->
        <view class="tab-panel" v-if="currentTab === 0">
          <view class="empty-state" v-if="favorites.length === 0">
            <u-icon name="star" size="60" color="#c0c4cc" />
            <view class="empty-text">暂无收藏的通货</view>
            <view class="empty-desc">快去首页收藏你关注的通货吧</view>
          </view>
          <view class="favorites-list" v-else>
            <view
              class="favorite-item"
              v-for="item in favorites"
              :key="item._id"
              @tap="goToCurrencyDetail(item)"
            >
              <image :src="item.icon_url" class="favorite-icon" mode="aspectFit" />
              <view class="favorite-info">
                <view class="favorite-name">{{ item.name }}</view>
                <view class="favorite-price">1元 = {{ formatPrice(item.price.cny_rate) }}个</view>
              </view>
              <view class="favorite-change" :class="item.price.trend">
                {{ item.price.change_percent > 0 ? '+' : '' }}{{ item.price.change_percent }}%
              </view>
            </view>
          </view>
        </view>

        <!-- 浏览历史 -->
        <view class="tab-panel" v-if="currentTab === 1">
          <view class="empty-state" v-if="history.length === 0">
            <u-icon name="clock" size="60" color="#c0c4cc" />
            <view class="empty-text">暂无浏览历史</view>
            <view class="empty-desc">浏览过的通货会出现在这里</view>
          </view>
          <view class="history-list" v-else>
            <view
              class="history-item"
              v-for="item in history"
              :key="item._id"
              @tap="goToCurrencyDetail(item)"
            >
              <image :src="item.icon_url" class="history-icon" mode="aspectFit" />
              <view class="history-info">
                <view class="history-name">{{ item.name }}</view>
                <view class="history-time">{{ formatTime(item.viewTime) }}</view>
              </view>
              <view class="history-price">{{ formatPrice(item.price.cny_rate) }}</view>
            </view>
          </view>
        </view>

        <!-- 设置 -->
        <view class="tab-panel" v-if="currentTab === 2">
          <view class="settings-list">
            <view class="setting-item" @tap="handleNotification">
              <view class="setting-left">
                <u-icon name="bell" size="20" color="#606266" />
                <view class="setting-name">价格提醒</view>
              </view>
              <view class="setting-right">
                <u-switch v-model="notificationEnabled" @change="toggleNotification" />
              </view>
            </view>

            <view class="setting-item" @tap="handleClearCache">
              <view class="setting-left">
                <u-icon name="trash" size="20" color="#606266" />
                <view class="setting-name">清除缓存</view>
              </view>
              <view class="setting-right">
                <u-icon name="arrow-right" size="16" color="#c0c4cc" />
              </view>
            </view>

            <view class="setting-item" @tap="handleFeedback">
              <view class="setting-left">
                <u-icon name="edit-pen" size="20" color="#606266" />
                <view class="setting-name">意见反馈</view>
              </view>
              <view class="setting-right">
                <u-icon name="arrow-right" size="16" color="#c0c4cc" />
              </view>
            </view>

            <view class="setting-item" @tap="handleAbout">
              <view class="setting-left">
                <u-icon name="info-circle" size="20" color="#606266" />
                <view class="setting-name">关于我们</view>
              </view>
              <view class="setting-right">
                <u-icon name="arrow-right" size="16" color="#c0c4cc" />
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-section" v-if="userInfo">
      <button class="logout-btn" @tap="handleLogout">退出登录</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: null,
      currentTab: 0,
      notificationEnabled: true,
      tabList: [
        { key: 'favorites', name: '我的收藏', icon: '⭐' },
        // { key: 'history', name: '浏览历史', icon: '🕒' },
        { key: 'settings', name: '设置', icon: '⚙️' }
      ],
      favorites: [],
      history: []
    }
  },

  onLoad() {
    this.checkLoginStatus()
  },

  onShow() {
    this.loadUserData()
  },

  methods: {
    // 检查登录状态
    checkLoginStatus() {
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo) {
        this.userInfo = userInfo
      }
    },

    // 加载用户数据
    loadUserData() {
      if (this.userInfo) {
        this.favorites = uni.getStorageSync('favorites') || []
        this.history = uni.getStorageSync('browseHistory') || []
      }
    },

    // 微信登录
    handleWechatLogin() {
      uni.login({
        provider: 'weixin',
        success: loginRes => {
          console.log('微信登录成功:', loginRes)
          // 这里可以调用后端接口进行登录验证
        },
        fail: err => {
          console.error('微信登录失败:', err)
          uni.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          })
        }
      })
    },

    // 获取用户信息
    onGetUserInfo(e) {
      console.log('e',e)
      if (e.detail) {
        const {avatarUrl} = e.detail
        const userInfo = {
         avatarUrl,
          loginTime: new Date().getTime(),
          level: 1
        }

        this.userInfo = userInfo
        uni.setStorageSync('userInfo', userInfo)

        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })

        // 加载用户数据
        this.loadUserData()
      }
    },

    // Tab切换
    handleTabChange(index) {
      this.currentTab = index
    },

    // 跳转到通货详情
    goToCurrencyDetail(currency) {
      uni.navigateTo({
        url: `/pages/index/index?currencyId=${currency._id}`
      })
    },

    // 格式化价格
    formatPrice(price) {
      if (price >= 1000) {
        return (price / 1000).toFixed(1) + 'K'
      } else if (price >= 1) {
        return price.toFixed(1)
      } else if (price >= 0.1) {
        return price.toFixed(2)
      } else {
        return price.toFixed(3)
      }
    },

    // 格式化时间
    formatTime(timestamp) {
      const now = new Date().getTime()
      const diff = now - timestamp

      if (diff < 60000) {
        return '刚刚'
      } else if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      } else {
        return Math.floor(diff / 86400000) + '天前'
      }
    },

    // 切换通知
    toggleNotification(value) {
      this.notificationEnabled = value
      uni.showToast({
        title: value ? '已开启价格提醒' : '已关闭价格提醒',
        icon: 'none'
      })
    },

    // 处理通知设置
    handleNotification() {
      // 跳转到通知设置页面或显示详细设置
    },

    // 清除缓存
    handleClearCache() {
      uni.showModal({
        title: '清除缓存',
        content: '确定要清除所有缓存数据吗？',
        success: res => {
          if (res.confirm) {
            uni.clearStorageSync()
            this.favorites = []
            this.history = []
            uni.showToast({
              title: '缓存已清除',
              icon: 'success'
            })
          }
        }
      })
    },

    // 意见反馈
    handleFeedback() {
      uni.navigateTo({
        url: '/pages/feedback/feedback'
      })
    },

    // 关于我们
    handleAbout() {
      uni.showModal({
        title: '关于POE2通货物价查询',
        content: '版本：1.0.0\n开发团队：POE2助手\n联系方式：support@poe2.com',
        showCancel: false
      })
    },

    // 退出登录
    handleLogout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: res => {
          if (res.confirm) {
            this.userInfo = null
            uni.removeStorageSync('userInfo')
            uni.showToast({
              title: '已退出登录',
              icon: 'success'
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.mine-container {
  background-color: #f5f6fa;
  min-height: 100vh;
  padding-bottom: 40rpx;
}

// 用户信息区域
.user-section {
  background: linear-gradient(135deg, #f4c242 0%, #f093fb 100%);
  padding: 60rpx 40rpx 40rpx;
  color: white;
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 20rpx;
}

.avatar-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.user-level {
  font-size: 24rpx;
  opacity: 0.9;
}

.user-stats {
  display: flex;
  gap: 40rpx;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 4rpx;
}

.stat-label {
  font-size: 22rpx;
  opacity: 0.9;
}

// 登录区域
.login-section {
  padding: 80rpx 40rpx;
}

.login-card {
  background: white;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.1);
}

.login-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.login-desc {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 60rpx;
}

.login-btn {
  background: #07c160;
  border: none;
  border-radius: 50rpx;
  padding: 24rpx;
  margin-bottom: 30rpx;
}

.btn-content {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.btn-text {
  font-size: 32rpx;
  margin-left: 12rpx;
}

.login-tip {
  font-size: 24rpx;
  color: #999;
}

// Tab切换栏
.tab-section {
  background: white;
  margin: 20rpx;
  border-radius: 15rpx;
  overflow: hidden;
}

.tab-header {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  transition: all 0.3s ease;

  &.active {
    color: #f4c242;

    .tab-icon {
      transform: scale(1.1);
    }

    .tab-name {
      font-weight: bold;
    }
  }
}

.tab-icon {
  font-size: 36rpx;
  margin-bottom: 8rpx;
  transition: all 0.3s ease;
}

.tab-name {
  font-size: 26rpx;
}

.tab-content {
  padding: 40rpx;
}

// 空状态
.empty-state {
  text-align: center;
  padding: 80rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #666;
  margin: 20rpx 0 10rpx;
}

.empty-desc {
  font-size: 24rpx;
  color: #999;
}

// 收藏列表
.favorites-list,
.history-list {
  .favorite-item,
  .history-item {
    display: flex;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }
  }

  .favorite-icon,
  .history-icon {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
    border-radius: 8rpx;
  }

  .favorite-info,
  .history-info {
    flex: 1;
  }

  .favorite-name,
  .history-name {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 8rpx;
  }

  .favorite-price,
  .history-time {
    font-size: 24rpx;
    color: #999;
  }

  .favorite-change,
  .history-price {
    font-size: 26rpx;
    font-weight: bold;

    &.up {
      color: #f56c6c;
    }
    &.down {
      color: #67c23a;
    }
    &.stable {
      color: #909399;
    }
  }
}

// 设置列表
.settings-list {
  .setting-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }
  }

  .setting-left {
    display: flex;
    align-items: center;
  }

  .setting-name {
    font-size: 28rpx;
    color: #333;
    margin-left: 20rpx;
  }
}

// 退出登录
.logout-section {
  padding: 0 40rpx;
  margin-top: 40rpx;
}

.logout-btn {
  background: #f56c6c;
  color: white;
  border: none;
  border-radius: 10rpx;
  padding: 24rpx;
  font-size: 28rpx;
  width: 100%;
}
</style>
